import os
from flask import jsonify, send_from_directory
from werkzeug.utils import secure_filename
from flask import Blueprint, request

from config import UPLOADED_PHOTOS_DEST
from module_admin.entity.do.base import db
from module_admin.entity.do.file import File
from module_admin.utils.http import success_api, table_api, fail_api

# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'txt', 'docx', 'xls', 'ppt', 'pptx', 'mp4', 'avi', 'mov'}

# 配置上传文件夹路径
# UPLOADED_PHOTOS_DEST = 'path/to/upload/folder'  # 请替换为实际路径

upload = Blueprint('upload', __name__)


# 检查文件类型是否允许
def allowed_file(filename):
    print(f"Checking file: {filename}")
    if '.' in filename:
        ext = filename.rsplit('.', 1)[1].lower()
        print(f"File extension: {ext}")
        return ext in ALLOWED_EXTENSIONS
    return False


# @upload.route('/upload1', methods=['POST'])
# def upload_file():
#     print(111)

@upload.route('/upload', methods=['POST'])
def upload_file():
    print(111)
    print(request.files)
    if 'file' not in request.files:
        return jsonify({"error": "No file part in the request"}), 400

    file = request.files['file']
    username = request.form.get('username')

    # 获取form_data中的type字段
    file_type = request.form.get('type')
    course_id = request.form.get('course_id')
    deadline = request.form.get('deadline')
    print(file_type)

    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # extension = filename.rsplit('.', 1)[1].lower()
        file_path = os.path.join(UPLOADED_PHOTOS_DEST, filename)

        # 检查并创建上传目录
        if not os.path.exists(UPLOADED_PHOTOS_DEST):
            os.makedirs(UPLOADED_PHOTOS_DEST)

        try:
            file.save(file_path)
        except Exception as e:
            return jsonify({"error": f"File saving failed: {str(e)}"}), 500

        file_size = os.path.getsize(file_path)

        new_file_record = File(
            type=file_type,
            original_name=file.filename,
            new_name=file.filename,
            extension="111",
            path="/static/upload/",
            url=f"/static/upload/{filename}",
            size=file_size,
            course_id=course_id,
            user_name=username,  # 替换为实际用户名
            create_by=1,  # 替换为实际用户ID
            dealine=deadline,  # 替换为实际用户ID
            update_by=1  # 替换为实际用户ID
        )

        try:
            db.session.add(new_file_record)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            return jsonify({"error": f"Database operation failed: {str(e)}"}), 500

        return success_api(msg=file_path)
    else:
        return jsonify({"error": "File type not allowed"}), 400


# 上传文件的接口
# @upload.route('/upload', methods=['POST'])
# def upload_file():
#     # 检查是否有文件
#     if 'file' not in request.files:
#         return jsonify({"error": "No file part in the request"}), 400
#
#     file = request.files['file']
#     # 获取form_data中的type字段
#     # file_type = request.form.get('type')
#     # print(file_type)
#
#     # 如果用户没有选择文件
#     if file.filename == '':
#         return jsonify({"error": "No selected file"}), 400
#
#     # 检查文件是否合法
#     if file and allowed_file(file.filename):
#         # 使用 secure_filename 确保文件名是安全的
#         filename = secure_filename(file.filename)
#         extension = filename.rsplit('.', 1)[1].lower()
#         file_path = os.path.join(UPLOADED_PHOTOS_DEST, filename)
#
#         # 保存文件
#         file.save(file_path)
#
#         # 获取文件大小
#         file_size = os.path.getsize(file_path)
#
#         # 构造文件记录对象
#         new_file_record = File(
#             # type=file_type,
#             original_name=filename,
#             new_name=filename,
#             extension=extension,
#             path="/static/upload/",
#             url=f"/static/upload/{filename}",
#             size=file_size,
#             user_name="UserNameExample",  # 假设可以获取用户名，这里用示例
#             create_by=1,  # 假设用户ID
#             update_by=1
#         )
#
#         # 保存到数据库
#         db.session.add(new_file_record)
#         db.session.commit()
#
#         # 返回上传成功的信息
#         return success_api(msg=file_path)
#     else:
#         return jsonify({"error": "File type not allowed"}), 400


# 下载文件的接口
@upload.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    try:
        # 使用 send_from_directory 函数来提供文件下载
        return send_from_directory(UPLOADED_PHOTOS_DEST, filename, as_attachment=True)
    except FileNotFoundError:
        return jsonify({"error": "File not found"}), 404


@upload.route('/file/get', methods=['GET'])
def get_files_by_type():
    # 从查询参数中获取 'type' 字段的值
    file_type = request.args.get('type', None)
    course_id = request.args.get('course_id', None)

    # 检查是否传入了 'type' 字段
    if not file_type:
        return jsonify({"error": "Type parameter is missing"}), 400

    try:
        # 过滤 File 表中 type 字段匹配的记录
        files = File.query.filter(File.type == file_type, File.course_id == course_id,File.original_name != 'answer.docx').all()
        from module_admin.entity.do.course import Course

        # 如果找不到匹配的文件
        if not files:
            return fail_api(msg="No file found")

        # 构造返回的数据
        file_list = []
        for file in files:
            # course = Course.query.filter(Course.id == file.course_id).first()
            file_data = {
                "id": file.id,
                "original_name": file.original_name,
                "new_name": file.new_name,
                "type": file.type,
                "extension": file.extension,
                "path": file.path,
                "url": file.url,
                "size": file.size,
                "user_name": file.user_name,
                "create_by": file.create_by,
                "update_by": file.update_by,
                "dealine": file.dealine
            }
            file_list.append(file_data)

        # 返回成功响应
        return table_api(
            data=file_list
        )

    except Exception as e:
        return fail_api(msg=str(e))


@upload.route('/file/delete/<int:file_id>', methods=['GET'])
def delete_file(file_id):
    try:
        # 查询要删除的文件记录
        file_to_delete = File.query.get(file_id)

        if file_to_delete is None:
            return jsonify({"error": "File not found"}), 404
        # 删除记录
        db.session.delete(file_to_delete)
        db.session.commit()

        return success_api(msg="File deleted successfully")

    except Exception as e:
        db.session.rollback()  # 回滚事务
        return jsonify({"error": str(e)}), 500
